<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleForm(false)"> 新增</a-button>
      </template>

      <template #levelWeight="{ record }">
        <span class="vip-name">
          {{ record.weightName }}
        </span>
      </template>

      <template #equity="{ record }">
        <div :class="`${prefixCls}-equity`">
          <div v-if="record.equityConsumeDiscount && record.equityConsumeDiscount !== 0"> 购物享 {{ record.equityConsumeDiscount }} 折优惠 </div>
          <div v-if="record.equityPointFeedback && record.equityPointFeedback !== 0"> 购物享 {{ record.equityPointFeedback }} 倍积分回馈 </div>
        </div>
      </template>

      <template #levelPack="{ record }">
        <div :class="`${prefixCls}-equity`">
          <div v-if="record.sendPoint && record.sendPoint !== 0"> 获赠 {{ record.sendPoint }} 积分 </div>
          <div v-if="record.sendBalance && record.sendBalance !== 0"> 获赠 {{ record.sendBalance }} 元红包 </div>
        </div>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" name="member-level" setup>
  import { ref, computed, unref } from "vue"
  import { BasicTable, TableAction, ActionItem, useTable, BasicColumn } from "/@/components/Table"
  import InputForm from "./Form.vue"
  import { useDesign } from "/@/hooks/web/useDesign"

  import { useDrawer } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { columns, searchFormSchema } from "./data"
  import { deleteLevel, listMemberLevel } from "/@/api/member/level.api"
  import { Icon } from "/@/components/Icon"
  import { useGo } from "/@/hooks/web/usePage"
  // import { usePermission } from '/@/hooks/web/usePermission'
  // const { hasPermission } = usePermission();
  const { prefixCls } = useDesign("member-level")
  const { createMessage, createConfirm } = useMessage()
  const go = useGo()
  const selectRows = ref([])
  const [registerDrawer, { openDrawer }] = useDrawer()
  const [registerModal, { openModal }] = useModal()

  const actionColumn: BasicColumn = {
    width: 150,
    title: "操作",
    dataIndex: "action",
    fixed: "right",
    slot: "tableActions",
    actions: (record) => [
      {
        label: "编辑",
        // auth: 'sys:area:update',
        onClick: handleForm.bind(null, true, record),
      },
      {
        label: "删除",
        color: "error",
        ifShow: record.sendStatus != 1,
        // auth: 'sys:area:delete',
        popConfirm: {
          title: "是否确认删除",
          confirm: handleDelete.bind(null, record),
        },
      },
    ],
    dropDownActions: (record: Recordable) => [],
  }

  const [registerTable, { reload, updateTableDataRecord, rowSelection, getSelectRowKeys }] = useTable({
    title: "会员等级",
    api: listMemberLevel,
    bordered: false,
    columns: columns,
    size: "small",
    formConfig: {
      baseColProps: { lg: 6, md: 12 },
      labelWidth: 90,
      schemas: searchFormSchema,
      showResetButton: false,
    },
    actionColumn,
    showTableSetting: true,
    useSearchForm: true,
    pagination: true,
    canResize: true,
    rowKey: "id",
    beforeFetch: (params) => {
      return Object.assign({ column: "createTime", order: "desc" }, params)
    },
  })

  function handleForm(isUpdate, record?: Recordable) {
    console.time("user-drawer")
    openDrawer(true, {
      record,
      isUpdate,
      showFooter: true,
    })
  }

  async function handleDetail(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
      showFooter: false,
    })
  }

  async function handleDelete(record) {
    if (record.isAdmin) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    await deleteLevel({ id: record.id }, reload)
  }

  function handleSuccess({ isUpdate, values }) {
    reload()
    if (isUpdate) {
      updateTableDataRecord(values.id, values)
      createMessage.success("编辑成功")
    } else {
      createMessage.success("新增成功")
    }
  }

  async function handleFrozen(record, status) {
    if (record.isAdmin) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    await frozenBatch({ ids: record.id, status: status }, reload)
  }
  /**
   * 批量冻结解冻
   */
  function batchFrozen(status) {
    let hasAdmin = unref(selectRows).filter((item) => item.isAdmin)
    if (unref(hasAdmin).length > 0) {
      createMessage.warning("管理员账号不允许此操作！")
      return
    }
    createConfirm({
      iconType: "warning",
      title: "确认操作",
      content: "是否" + (status == 1 ? "解冻" : "冻结") + "选中账号?",
      onOk: async () => {
        await frozenBatch({ ids: unref(selectedRowKeys).join(","), status: status }, reload)
      },
    })
  }

  /**
   *同步钉钉和微信回调
   */
  function onSyncFinally({ isToLocal }) {
    // 同步到本地时刷新下数据
    if (isToLocal) {
      reload()
    }
  }

  const checkeUser = (record) => {
    // 不能操作租户拥有者, 其余都可以操作
    return record.roleList
      .map((e) => e.roleCode)
      .join(",")
      .includes("owner")
  }

  function getTableAction(record): ActionItem[] {
    return [
      {
        label: "编辑",
        onClick: handleEdit.bind(null, record),
        ifShow: () => !checkeUser(record),
      },
      {
        label: "详情",
        onClick: handleDetail.bind(null, record),
      },
    ]
  }
</script>

<style lang="less">
  @prefix-cls: ~"@{namespace}-app-search-footer";

  .vip-name {
    color: #b38f47;
  }
  .@{prefix-cls} {
    &-equity {
      line-height: 1.6;
    }
  }
</style>
